package com.softtown.modules.sys.controller;

import com.github.pagehelper.PageInfo;
import com.softtown.common.annotation.LogOperation;
import com.softtown.common.exception.ErrorCode;
import com.softtown.common.utils.IdWorker;
import com.softtown.common.utils.Result;
import com.softtown.common.validator.ValidatorUtils;
import com.softtown.modules.organization.entity.CompOrgEmplEntity;
import com.softtown.modules.organization.service.CompOrgEmplService;
import com.softtown.modules.oss.cloud.OSSFactory;
import com.softtown.modules.oss.entity.SysOssFileEntity;
import com.softtown.modules.sys.dto.CompSysUserEmplInfoDTO;
import com.softtown.modules.sys.dto.CompSysUserEmplPageDTO;
import com.softtown.modules.sys.dto.SysUserDTO;
import com.softtown.modules.sys.entity.CompSysUserEmplEntity;
import com.softtown.modules.sys.entity.SysUserEntity;
import com.softtown.modules.sys.service.CompSysUserEmplService;
import com.softtown.modules.sys.service.SysParamsService;
import com.softtown.modules.sys.service.SysUserService;
import com.softtown.modules.sys.vo.CompSysUserEmplBasicsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.Objects;
import javax.annotation.Resource;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 公司员工
 *
 * @author Dingyayong
 * @version v1.0
 * @create 2019-06-23 16:38
 **/
@RestController
@RequestMapping("comp/empl")
@Api(tags = "公司员工")
public class CompSysUserEmplController {

    @Resource
    CompSysUserEmplService compSysUserEmplService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private CompOrgEmplService compOrgEmplService;

    @Resource
    private SysParamsService sysParamsService;

    private static final String CLOUD_STORAGE__SERVICE_IS_USABLE = "STORAGE__SERVICE_IS_USABLE";
    private static final String YES = "Y";

    @PostMapping("getEmplList")
    @ApiOperation("公司用户分页")
    @LogOperation("公司用户分页")
    public Result getRoleUsers(@RequestBody CompSysUserEmplPageDTO compSysUserEmplPageDTO) {
        return new Result<PageInfo<CompSysUserEmplEntity>>().ok(compSysUserEmplService.findUserPage(compSysUserEmplPageDTO));
    }

    @PostMapping("getCompUserList")
    @ApiOperation("公司用户")
    @LogOperation("公司用户")
    public Result<List<SysUserEntity>> getCompUserList(@RequestBody String compId) {
        String companyId = JSONObject.fromObject(compId).get("compId").toString();
        List<CompSysUserEmplEntity> compSysUserEmplEntities = compSysUserEmplService.findAllCompEmpl(Long.valueOf(companyId));
        List<SysUserEntity> userEntities = new ArrayList<>();
        for (CompSysUserEmplEntity compSysUserEmplEntity : compSysUserEmplEntities) {
            userEntities.add(sysUserService.getByUserId(compSysUserEmplEntity.getUserId()));
        }
        return new Result<List<SysUserEntity>>().ok(userEntities);
    }

    @PostMapping("activate")
    @ApiOperation("公司用户激活")
    @LogOperation("公司用户激活")
    public Result activate(@RequestBody String id) {
        String userId = JSONObject.fromObject(id).get("id").toString();
        String compId = JSONObject.fromObject(id).get("compId").toString();
        return compSysUserEmplService.activate(Long.valueOf(compId), Long.valueOf(userId));
    }

    @PostMapping("updateEmplInfo")
    @ApiOperation("更新")
    @LogOperation("更新")
    public Result updateEmplInfo(@RequestBody SysUserDTO sysUserDTO) {
        compSysUserEmplService.updateEmplInfo(sysUserDTO);
        return new Result<>();
    }

    @PostMapping("findAllCompEmpl")
    @ApiOperation("查询员工")
    @LogOperation("查询员工")
    public Result<List<CompOrgEmplEntity>> findAllCompEmpl(@RequestBody String compId) {
        String id = JSONObject.fromObject(compId).get("compId").toString();
        List<CompOrgEmplEntity> compOrgEmplEntities = compOrgEmplService.findByCompId(Long.valueOf(id));
        return new Result<List<CompOrgEmplEntity>>().ok(compOrgEmplEntities);
    }

    @PostMapping("findAllCompEmplByBene")
    @ApiOperation("查询没有收款信息的员工")
    @LogOperation("查询没有收款信息的员工")
    public Result<List<CompOrgEmplEntity>> findAllCompEmplByBene(@RequestBody String compId) {
        String id = JSONObject.fromObject(compId).get("compId").toString();
        List<CompOrgEmplEntity> compOrgEmplEntities = compOrgEmplService.findAllCompEmplByBene(Long.valueOf(id));
        return new Result<List<CompOrgEmplEntity>>().ok(compOrgEmplEntities);
    }

    @PostMapping("addEmplInfo")
    @ApiOperation("新增")
    @LogOperation("新增")
    public Result addEmplInfo(@RequestBody SysUserDTO sysUserDTO) {
        Result result = new Result<>();
        if (!sysUserDTO.getUsername().isEmpty()) {
            SysUserDTO userDTO = sysUserService.getByUsername(sysUserDTO.getUsername());
            if (userDTO != null) {
                return result.error(ErrorCode.USERNAME_EXISTS);
            }
        }
        if (!sysUserDTO.getMobile().isEmpty()) {
            SysUserEntity sysUserEntity = sysUserService.getEntityByMobile(sysUserDTO.getMobile());
            if (sysUserEntity != null) {
                return result.error(ErrorCode.USER_MOBILE_EXISTS);
            }
        }
        if (!sysUserDTO.getEmail().isEmpty()) {
            SysUserEntity sysUserEntity1 = sysUserService.getEntityByEmail(sysUserDTO.getEmail());
            if (sysUserEntity1 != null) {
                return result.error(ErrorCode.USER_EMAIL_EXISTS);
            }
        }
        if (!sysUserDTO.getPassword().equals(sysUserDTO.getComfirmPassword())) {
            return result.error(ErrorCode.PASSWORD_SAME_ERROR);
        }
        compSysUserEmplService.addEmplInfo(sysUserDTO);
        return result;
    }

    @PostMapping("upload")
    @ApiOperation("上传头像")
    @LogOperation("上传头像")
    public Result upload(@RequestBody MultipartFile file) {
        String url = null;
        String fileName = "0000000000000000000";
        String sysUser = "sys_user";
        long fileId = IdWorker.getId();
        Result result = new Result<>();
        try {
            String flag = sysParamsService.getValue(CLOUD_STORAGE__SERVICE_IS_USABLE);
            if (flag.equals(YES)) {
                url = Objects.requireNonNull(OSSFactory.build())
                        .upload(file.getInputStream(), fileName + "/" +sysUser+"/"+ fileId + "_" + file.getOriginalFilename());
            } else {
                return result.error(ErrorCode.STORAGE_SERVICE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.ok(url);
    }

    @PostMapping("uploadEmpl")
    @ApiOperation("上传员工图像")
    @LogOperation("上传员工图像")
    public Result uploadEmpl(@RequestBody MultipartFile file) {
        String url = null;
        String fileName = "0000000000000000000";
        String sysDoc = "comp_org_empl";
        long fileId = IdWorker.getId();
        Result result = new Result<>();
        try {
            String flag = sysParamsService.getValue(CLOUD_STORAGE__SERVICE_IS_USABLE);
            if (flag.equals(YES)) {
                url = Objects.requireNonNull(OSSFactory.build())
                        .upload(file.getInputStream(), fileName + "/"+sysDoc +"/"+ fileId + "_" + file.getOriginalFilename());
            } else {
                return result.error(ErrorCode.STORAGE_SERVICE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.ok(url);
    }

    @PostMapping("uploadAott")
    @ApiOperation("上传反馈附件")
    @LogOperation("上传反馈附件")
    public Result uploadAott(@RequestBody MultipartFile file) {
        String url = null;
        String fileName = "0000000000000000000";
        String sysDoc = "sys_doc_att";
        long fileId = IdWorker.getId();
        Result result = new Result<>();
        try {
            String flag = sysParamsService.getValue(CLOUD_STORAGE__SERVICE_IS_USABLE);
            if (flag.equals(YES)) {
                url = Objects.requireNonNull(OSSFactory.build())
                        .upload(file.getInputStream(), fileName + "/"+sysDoc +"/"+ fileId + "_" + file.getOriginalFilename());
            } else {
                return result.error(ErrorCode.STORAGE_SERVICE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.ok(url);
    }


    @PostMapping("uploadFile")
    @ApiOperation("上传附件")
    @LogOperation("上传附件")
    public Result uploadFile(@RequestBody MultipartFile file, HttpServletRequest request) {
        String url = null;
        long fileId = IdWorker.getId();
        String compId = request.getParameter("compId");
        Result result = new Result<>();
        try {
            String flag = sysParamsService.getValue(CLOUD_STORAGE__SERVICE_IS_USABLE);
            if (flag.equals(YES)) {
                if (compId != null) {
                    url = Objects.requireNonNull(OSSFactory.build())
                            .upload(file.getInputStream(), compId + "/" + fileId + "_" + file.getOriginalFilename());
                } else {
                    url = Objects.requireNonNull(OSSFactory.build())
                            .upload(file.getInputStream(), fileId + "_" + file.getOriginalFilename());
                }
            } else {
                return result.error(ErrorCode.STORAGE_SERVICE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.ok(url);
    }

    @PostMapping("deleteFile")
    @ApiOperation("删除附件")
    @LogOperation("删除附件")
    public Result deleteFile(@RequestBody String compId) {
        String comp = JSONObject.fromObject(compId).get("compId").toString();
        String url = JSONObject.fromObject(compId).get("url").toString();
        int endLast = url.lastIndexOf("/");
        try {
            Objects.requireNonNull(OSSFactory.build())
                    .deleteFile(comp + "/" + url.substring(endLast + 1));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<>();
    }

    @PostMapping("returnUrl")
    @ApiOperation("返回附件地址")
    @LogOperation("返回附件地址")
    public Result<String> returnUrl(@RequestBody String path) {
        String filePath = "";
        String url = JSONObject.fromObject(path).get("filePath").toString();
        try {
            filePath = Objects.requireNonNull(OSSFactory.build()).getHeadUrl(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<String>().ok(filePath);
    }

    @PostMapping("returnFileUrl")
    @ApiOperation("返回文件附件地址")
    @LogOperation("返回文件附件地址")
    public Result<SysOssFileEntity> returnFileUrl(@RequestBody String path) {
        SysOssFileEntity sysOssFileEntity = new SysOssFileEntity();
        String url = JSONObject.fromObject(path).get("filePath").toString();
        try {
            sysOssFileEntity = Objects.requireNonNull(OSSFactory.build()).getStsToken(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<SysOssFileEntity>().ok(sysOssFileEntity);
    }

    @PostMapping("BothDeleteFile")
    @ApiOperation("循环删除附件")
    @LogOperation("循环删除附件")
    public Result bothDeleteFile(@RequestBody String compId) {
        String comp = JSONObject.fromObject(compId).get("compId").toString();
        String url = JSONObject.fromObject(compId).get("url").toString();
        return new Result<>();
    }

    @PostMapping("getEmplInfo")
    @ApiOperation("获取用户的员工信息")
    @LogOperation("获取用户的员工信息")
    public Result getEmplInfo(@RequestBody CompSysUserEmplInfoDTO compSysUserEmplInfoDTO) {
        ValidatorUtils.validateEntity(compSysUserEmplInfoDTO);
        return compSysUserEmplService.getCompUserEmplBasics(compSysUserEmplInfoDTO);
    }
}

